package com.app.h5.util;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import java.util.List;
import java.util.Map;

/**
 * Created by Dave on 2020/6/8.
 */
public class GsonUtil {
    public static final String TAG = "GSON_LOG";
    private static volatile Gson gson;
    private static volatile Gson gsonNoCrash;

    /**
     * 常规gson
     *
     * @return
     */
    public static Gson getInstance() {
        if (gson == null) {
            synchronized (GsonUtil.class.getName()) {
                if (gson == null) {
                    gson = new GsonBuilder().serializeNulls().create();
                }
            }
        }
        return gson;
    }

    /**
     * @param obj
     * @return
     */
    public static String toJson(Object obj) {
        try {
            if (obj == null) {
                return "";
            }
            return getInstance().toJson(obj);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * @param content
     * @param obj
     * @return
     */
    public static <T> T fromJsonObj(String content, Class<T> obj) {
        try {
            if (TextUtils.isEmpty(content) || obj == null) {
                return null;
            }
            return getInstance().fromJson(content, obj);
        } catch (JsonSyntaxException e) {
            return null;
        }
    }

    /**
     * @param content
     * @param obj
     * @return
     */
    public static <T> List<T> fromJsonList(String content, Class<T> obj) {
        try {
            if (TextUtils.isEmpty(content) || obj == null) {
                return null;
            }
            return getInstance().fromJson(content, TypeToken.getParameterized(List.class, obj).getType());
        } catch (JsonSyntaxException e) {
            return null;
        }
    }

    /**
     * @param content
     * @param key
     * @param value
     * @return
     */
    public static <T, S> Map<T, S> fromJsonMap(String content, Class<T> key, Class<S> value) {
        try {
            if (TextUtils.isEmpty(content) || key == null || value == null) {
                return null;
            }
            return getInstance().fromJson(content, TypeToken.getParameterized(Map.class, key, value).getType());
        } catch (JsonSyntaxException e) {
            return null;
        }
    }
}
